package com.lixixi.tingshu.order.listener;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lixixi.tingshu.common.constant.KafkaConstant;
import com.lixixi.tingshu.common.constant.RedisConstant;
import com.lixixi.tingshu.common.constant.SystemConstant;
import com.lixixi.tingshu.model.order.OrderInfo;
import com.lixixi.tingshu.order.service.OrderInfoService;
import jakarta.annotation.PostConstruct;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class OrderStatusListener {

	@Autowired
	RedissonClient redissonClient;

	@Autowired
	OrderInfoService orderInfoService;

	@Autowired
	KafkaTemplate kafkaTemplate;

	/**
	 * 创建一个线程监听redisson延迟队列消息
	 */
	@PostConstruct
	void redissonDelayQueueConsumer() {
		ExecutorService executorService = Executors.newFixedThreadPool(1);
		executorService.submit(() -> {
			while (true)
			{
				RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque(RedisConstant.ORDER_DELAY_QUEUE);
				String orderInfoJson = blockingDeque.take();
				kafkaTemplate.send(orderInfoJson, KafkaConstant.QUEUE_ORDER_CANCEL);
				//休眠500ms
				Thread.sleep(500);
			}
		});
	}

	/**
	 * 监听redisson延迟队列发送的订单id, 检测支付超时状态
	 * @param orderIdStr
	 */
	@KafkaListener(groupId = KafkaConstant.QUEUE_ORDER_CANCEL, topics = KafkaConstant.QUEUE_ORDER_CANCEL)
	void cancelOrder(String orderIdStr) {
		try
		{
			OrderInfo orderInfo = orderInfoService.getById(Long.parseLong(orderIdStr));
			String orderStatus = orderInfo.getOrderStatus();
			if (SystemConstant.ORDER_STATUS_UNPAID.equals(orderStatus))
			{
				boolean update = orderInfoService.update(new LambdaUpdateWrapper<OrderInfo>()
						.eq(OrderInfo::getId, orderInfo.getId())
						.set(OrderInfo::getOrderStatus, SystemConstant.ORDER_STATUS_CANCEL)
						.set(OrderInfo::getOrderStatusName, "已取消"));
			}
		} catch (Exception e)
		{
			//将消息发送至死信队列
			//发送短信通知管理员
			e.printStackTrace();
		}
	}
}
